﻿ 
using System; 
using System.Collections.Generic; 
using System.Text; 
using System.IO; 
using System.Security.Cryptography; 
using System.Text.RegularExpressions;//正则表达式命名空间 

namespace XISoft.AppCreator.Util.Libiary
{ 
    /// <summary> 
    /// 计算判断公共类 
    /// 所括：电话号码判断、电子邮件判断、身份证合法性判断、身份证内部信息提取、 
    /// 判断文本是否全是数字组合、文本是否纯数字组合、是否纯字母组合、是否是数字(含小数位) 
    /// 对称加密解密、非对称加密、返回文本中的数字部分(适合double与int) 
    /// </summary> 
    public class ComputeClass 
    { 
        #region 电话号码判断 
        /// <summary> 
        /// 名称：CheckPhoneNumber 
        /// 方法：判断是否合法的电话号码 
        /// </summary> 
        /// <param name="number">所要判断的电话号码或手机号码 </param> 
        /// <returns>true,false </returns> 
        public static bool CheckPhoneNumber(string number) 
        { 
            if (System.Text.RegularExpressions.Regex.IsMatch(number, @"^(?:0(?:10|2[0-57-9]|[3-9]\d{2})[-—]?)\d{7,8}$")) 
            { 
                return true; 
            } 
            else if (System.Text.RegularExpressions.Regex.IsMatch(number, "^1\\d{10}$"))   
            { 
                return true; 
            } 
            else 
            { 
                return false; 
            } 
        } 
        #endregion 

        #region 电子邮件判断 
        /// <summary> 
        /// 名称：CheckEmail 
        /// 功能：判断是否正确的电子邮件 
        /// </summary> 
        /// <param name="inputEmail">所要判断的电子邮件号 </param> 
        /// <returns>true,false </returns> 
        public static bool CheckEmail(string inputEmail) 
        { 
            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; 
            Regex re = new Regex(strRegex); 
            if (re.IsMatch(inputEmail)) 
            { 
                return true; 
            } 
            else 
            { 
                return false; 
            } 
        } 
        #endregion 

        #region 身份证内信息提取 
        /// <summary> 
        /// 名称：CheckPassPortChina 
        /// 功能：检查中国公民身份证是否正确 
        /// </summary> 
        /// <param name="cid">需检查的身份证号码 </param> 
        /// <returns>返回由省市，生日，性别组成的字符串 </returns> 
        private string CheckPassPortChina(string cid) 
        { 
            string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" }; 
            double iSum = 0; 
            System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{17}(\d|x)$"); 
            System.Text.RegularExpressions.Match mc = rg.Match(cid); 
            if (!mc.Success) 
            { 
                return ""; 
            } 
            cid = cid.ToLower(); 
            cid = cid.Replace("x", "a"); 
            if (aCity[int.Parse(cid.Substring(0, 2))] == null) 
            { 
                return "非法地区"; 
            } 
            try 
            { 
                DateTime.Parse(cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2)); 
            } 
            catch 
            { 
                return "非法生日"; 
            } 
            for (int i = 17; i >= 0; i--) 
            { 
                iSum += (System.Math.Pow(2, i) % 11) * int.Parse(cid[17 - i].ToString(), System.Globalization.NumberStyles.HexNumber); 
            } 
            if (iSum % 11 != 1) 
            { 
                return ("非法证号"); 
            } 

            return (aCity[int.Parse(cid.Substring(0, 2))] + "," + cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2) + "," + (int.Parse(cid.Substring(16, 1)) % 2 == 1 ? "男" : "女")); 
        } 
        #endregion 

        #region 检查身分证的合法性 
        /// <summary> 
        /// 名称：CheckCidInfo 
        /// 功能：检查中国公民身份证号码 
        /// </summary> 
        /// <param name="cid">需检查的身份证号 </param> 
        /// <returns>true,false </returns> 
        private bool CheckCidInfo(string cid) 
        { 
            string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" }; 
            double iSum = 0; 
            System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{17}(\d|x)$"); 
            System.Text.RegularExpressions.Match mc = rg.Match(cid); 
            if (!mc.Success) 
            { 
                return false; ; 
            } 
            cid = cid.ToLower(); 
            cid = cid.Replace("x", "a"); 
            if (aCity[int.Parse(cid.Substring(0, 2))] == null) 
            { 
                return false; 
            } 
            try 
            { 
                DateTime.Parse(cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2)); 
            } 
            catch 
            { 
                return false; 
            } 
            for (int i = 17; i >= 0; i--) 
            { 
                iSum += (System.Math.Pow(2, i) % 11) * int.Parse(cid[17 - i].ToString(), System.Globalization.NumberStyles.HexNumber); 

            } 
            if (iSum % 11 != 1) 
                return (false); 
            //return (aCity[int.Parse(cid.Substring(0, 2))] + "," + cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2) + "," + (int.Parse(cid.Substring(16, 1)) % 2 == 1 ? "男" : "女")); 
            return true; 
        } 
        #endregion 

        #region 判断文本是否全是字母组合 
        /// <summary> 
        /// 名称：IsAllChar 
        /// 判断文本是否全是字母组合 
        /// </summary> 
        /// <param name="text">需判断的文本或是字符串 </param> 
        /// <returns>返回true代表全是字母组合 </returns> 
        public static bool IsAllChar(string text) 
        { 
            foreach(char tempchar in text.ToCharArray()) 
            { 
                if (!char.IsLetter(tempchar)) 
                { 
                    return false; 
                } 
            } 
            return true; 
        } 
        #endregion 

        #region 判断文本是否纯数字组合 
        /// <summary> 
        /// 名称：IsAllNumber 
        /// 判断文本是否全数字组成函数1(推荐使用) 
        /// </summary> 
        /// <param name="text">需判断的文本或字符串 </param> 
        /// <returns>返回true代表纯数字，否则为非纯数字 </returns> 
        public static bool IsAllNumber(string text) 
        { 
            foreach(char tempchar in text.ToCharArray()) 
            { 
                if (tempchar == '.') 
                { 
                    return false; 
                } 
            } 
            Regex objNotNumberPattern = new Regex("[^0-9.-]"); 
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*"); 
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*"); 
            String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$"; 
            String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$"; 
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")"); 
            return !objNotNumberPattern.IsMatch(text) && !objTwoDotPattern.IsMatch(text) && !objTwoMinusPattern.IsMatch(text) && objNumberPattern.IsMatch(text); 
        } 
        #endregion 

        #region 判断文本是否是数字(包括小数位的判断)
        /// <summary> 
        /// 名称：IsNumber 
        /// 判断是否数字函数1(推荐使用) 
        /// </summary> 
        /// <param name="text">需判断的文本或字符串 </param> 
        /// <returns>返回true代表数字，否则为非数字 </returns> 
        public static bool IsNumber(string text)
        {
            Regex objNotNumberPattern = new Regex("[^0-9.-]");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
            String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
            String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
            return !objNotNumberPattern.IsMatch(text) && !objTwoDotPattern.IsMatch(text) && !objTwoMinusPattern.IsMatch(text) && objNumberPattern.IsMatch(text);
        }
        #endregion

        #region 对称加密解密
        /// <summary> 
        /// 名称：Encrypt 
        /// DES对称加密函数1 
        /// </summary> 
        /// <param name="str">需加密字符串 </param> 
        /// <param name="pkey">密匙 </param> 
        /// <returns>返回用指定密匙加密的字符串 </returns> 
        public static string Encrypt(string str, string pkey)
        {
            try
            {
                byte[] bt = (new System.Text.UnicodeEncoding()).GetBytes(str);
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(pkey, null);
                byte[] key = pdb.GetBytes(24);
                byte[] iv = pdb.GetBytes(8);
                MemoryStream ms = new MemoryStream();
                TripleDESCryptoServiceProvider tdesc = new TripleDESCryptoServiceProvider();
                CryptoStream cs = new CryptoStream(ms, tdesc.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                cs.Write(bt, 0, bt.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary> 
        /// 名称：Decrypt 
        /// DES对称加密函数1 
        /// </summary> 
        /// <param name="str">需解密字符串 </param> 
        /// <param name="pkey">密匙 </param> 
        /// <returns>返回用指定密匙解密的字符串 </returns> 
        public static string Decrypt(string str, string pkey)
        {
            try
            {
                byte[] bt = Convert.FromBase64String(str);
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(pkey, null);
                byte[] key = pdb.GetBytes(24);
                byte[] iv = pdb.GetBytes(8);
                MemoryStream ms = new MemoryStream();
                TripleDESCryptoServiceProvider tdesc = new TripleDESCryptoServiceProvider();
                CryptoStream cs = new CryptoStream(ms, tdesc.CreateDecryptor(key, iv), CryptoStreamMode.Write);
                cs.Write(bt, 0, bt.Length);
                cs.FlushFinalBlock();
                return (new System.Text.UnicodeEncoding()).GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary> 
        /// 名称：EncryptOne 
        /// DES对称加密函数2 
        /// </summary> 
        /// <param name="strPass">需加密字符串 </param> 
        /// <param name="strKey">密匙 </param> 
        /// <returns>返回用指定密匙加密的字符串 </returns> 
        public static string EncryptOne(string strPass, string strKey)
        {
            int keyLen = strKey.Length;
            char[] strResult = strPass.ToCharArray();
            for (int i = 0; i < strPass.Length; i++)
            {
                char chKey = strKey[i % keyLen];
                if (i != 0)
                {
                    if (strResult[i] != (char)(chKey ^ strResult[i - 1]))
                    {
                        strResult[i] = (char)(strResult[i] ^ chKey ^ strResult[i - 1]);
                    }
                }
                else
                {
                    if (strResult[i] != chKey)
                    {
                        strResult[i] = (char)(strResult[i] ^ chKey);
                    }
                }
            }
            return new string(strResult);
        }

        /// <summary> 
        /// 名称：DecryptOne 
        /// DES对称解密函数2 
        /// </summary> 
        /// <param name="strPass">需解密字符串 </param> 
        /// <param name="strKey">密匙 </param> 
        /// <returns>返回用指定密匙解密的字符串 </returns> 
        public static string DecryptOne(string strPass, string strKey)
        {
            int keyLen = strKey.Length;
            char[] strResult = strPass.ToCharArray();
            for (int i = strPass.Length - 1; i >= 0; i--)
            {
                char chKey = strKey[i % keyLen];
                if (i != 0)
                {
                    if (strResult[i] != (char)(chKey ^ strResult[i - 1]))
                    {
                        strResult[i] = (char)(strResult[i] ^ chKey ^ strResult[i - 1]);
                    }
                }
                else
                {
                    if (strResult[i] != chKey)
                    {
                        strResult[i] = (char)(strResult[i] ^ chKey);
                    }
                }
            }
            return new string(strResult);
        }
        #endregion

        #region 非对称MD5加密
        /// <summary> 
        /// 名称：BBMD5 
        /// MD5非对称加密算法 
        /// </summary> 
        /// <param name="str">需加密字符串 </param> 
        /// <returns>返回加密字符串 </returns> 
        public static string BBMD5(string str)
        {
            string pwd = "";
            MD5 md5 = MD5.Create();//实例化一个md5对像 
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　 
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得 
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 
                pwd = pwd + s[i].ToString("X");
            }
            return pwd;
        }
        #endregion

        #region 全汉字判断
        /// <summary> 
        /// 名称：IsAllChina 
        /// 判断是否全是汉字组合 
        /// </summary> 
        /// <param name="text">需判断的文本 </param> 
        /// <returns>返回True为全是汉字组合 </returns> 
        public static bool IsAllChina(string text)
        {
            foreach (char c in text.ToCharArray())
            {
                if (Regex.IsMatch(c.ToString(), @"^[\u4e00-\u9fa5]+$") == false)
                {
                    return false;
                }
            }
            return true;
        }

        public bool IsAllChinese(string text)
        {
            return Regex.IsMatch(text, @"^[\u4e00-\u9fa5]+$");
        }
        #endregion


      

        #region 返回文本中的数字部分(适合double与int)
        /// <summary> 
        /// 方法名称：GetDoubleNumber 
        /// 功能：从数字和字母组合中返回带小数位的数字(移除非数字部分) 
        /// </summary> 
        /// <param name="text">所要进行处理的字符串 </param> 
        /// <returns>返回double的数字 </returns> 
        public static double GetDoubleNumber(string text)
        {
            double result = 0;
            if (text != null && text != string.Empty)
            {
                // 正则表达式剔除非数字字符（不包含小数点.） 
                text = Regex.Replace(text, @"[^\d.\d]", "");
                // 如果是数字，则转换为int类型 
                if (Regex.IsMatch(text, @"^[+-]?\d*[.]?\d*$"))
                {
                    result = double.Parse(text);
                }
            }
            return result;
        }

        /// <summary> 
        /// 方法名称：GetIntNumber 
        /// 功能：从数字和字母组合中返回整型数字(移除非数字部分) 
        /// </summary> 
        /// <param name="text">所要进行处理的字符串 </param> 
        /// <returns>返回整型数字 </returns> 
        public static int GetIntNumber(string text)
        {
            int result = 0;
            if (text != null && text != string.Empty)
            {
                // 正则表达式剔除非数字字符（不包含小数点.） 
                text = Regex.Replace(text, @"[^\d.\d]", "");
                // 如果是数字，则转换为int类型 
                if (Regex.IsMatch(text, @"^[+-]?\d*[.]?\d*$"))
                {
                    result = int.Parse(text);
                }
            }
            return result;
        }
        #endregion

    }
}
